import { Command } from '../constant';
import Taro from '@tarojs/taro';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';
import config from '@/service/config';
import { pvUvStatics, WMkit, wxShare, _, msg } from 'wmkit';
import RSAKey from 'react-native-rsa';
import { generateUUID } from '@/utils/getUniqueID';
import api from 'api';
import moment from 'dayjs';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async getMemberEquityNum(login: boolean) {
      const lanjingLength = await api.MemberController.getMemberEquityNum2(0, 0);
      const chijingLength = await api.MemberController.getMemberEquityNum2(1, 0);
      const shaungchongLength = await api.MemberController.getMemberEquityNum2(2, 0);

      if (typeof lanjingLength === 'number' && typeof chijingLength === 'number') {
        dispatch({
          type: Command.init,
          payload: {
            main: {
              lanjingLength: lanjingLength || '0',
              chijingLength: chijingLength || '0',
              shaungchongLength: shaungchongLength || '0',
            },
          },
        });
      }
    },
    async getLotteryButtonShow() {
      const result = await api.MemberController.getLotteryButtonShow();
      if (result) {
        dispatch({
          type: Command.init,
          payload: {
            main: {
              showDayLotteryButton: result,
            },
          },
        });
      }
    },
    async getMemberBase() {
      const {
        main: { memberCardType: memberCardType_old },
      } = getData();
      const result = await api.MemberController.getMemberBase();
      let memberCardType = 'noMember';
      // let isAquamarineMember = false,
      // isCrystalMember = false;
      if (result.isAquamarineMember) {
        memberCardType = 'lanjing';
        // isAquamarineMember = true;
        // isCrystalMember = false;
      }
      if (result.isCrystalMember) {
        memberCardType = 'chijing';
        // isAquamarineMember = false;
        // isCrystalMember = true;
      }
      if (result.isAquamarineMember && result.isCrystalMember) {
        memberCardType = 'shuangchong';
        // isAquamarineMember = true;
        // isCrystalMember = true;
      }
      const selectMemberCard = memberCardType;
      let renewalMemberModel = false;
      let renewalMemberModeldate = Taro.getStorageSync('renewalMemberModeldate');
      if (!renewalMemberModeldate && result.isPop) {
        //未缓存时间&&已到设置到期时间（出现到期弹框）
        renewalMemberModel = true;
      } else if (renewalMemberModeldate != moment(new Date()).format('YYYY-MM-DD') && result.isPop) {
        //缓存时间不一致（已到第二天）&&已到设置到期时间（出现到期弹框）
        renewalMemberModel = true;
      }
      let joinMemberModel = false;
      if (!result.isAquamarineMember && !result.isCrystalMember && !Taro.getStorageSync('joinMemberModel')) {
        joinMemberModel = true;
      }
      const dispatchData = {
        memberInfo: result,
        renewalMemberModel,
        joinMemberModel,
        // isAquamarineMember,
        // isCrystalMember,
      };
      if (memberCardType_old !== memberCardType) {
        Reflect.set(dispatchData, 'memberCardType', memberCardType);
        Reflect.set(dispatchData, 'selectMemberCard', selectMemberCard);
        // Reflect.set(dispatchData, 'isAquamarineMember', isAquamarineMember);
        // Reflect.set(dispatchData, 'isCrystalMember', isCrystalMember);
      }
      // {
      //   memberCardType,

      // },
      dispatch({
        type: Command.init,
        payload: {
          main: dispatchData,
        },
      });
      this.findMarketingcontentPage(); //查询内容营销
    },
    /**
     * 获取AES key
     */
    async getAPPSecret() {
      const bits = 1024;
      const exponent = '10001'; // must be a string. This is hex string. decimal = 65537
      let rsa = new RSAKey();
      rsa.generate(bits, exponent);
      var publicKey = rsa.getPublicString(); // return json encoded string
      var privateKey = rsa.getPrivateString(); // return json encoded string
      let uniqueID;
      if (Taro.getStorageSync('uniqueID')) {
        uniqueID = Taro.getStorageSync('uniqueID');
      } else {
        uniqueID = generateUUID();
        Taro.setStorageSync('uniqueID', uniqueID);
      }
      const params = {
        pubKey: JSON.parse(publicKey).n,
        deviceCode: uniqueID,
      };
      let res = await api.pagesIndexController.getAesKey(params);
      if (res.success && res.code == '200') {
        let aesKey = rsa.decrypt(res.data.key);
        Taro.setStorageSync('aesKey', aesKey);
        //延迟防止请求失败
        setTimeout(() => {
          //获取社区名称
          this.getSelectDistance();
        }, 100);
      } else {
        Taro.removeStorage({ key: 'aesKey' });
      }
    },
    /**
     * 获取社区名称
     */
    async getSelectDistance() {
      let obj = {
        distance: '',
        id: '',
        code: '',
        latitude: '',
        longitude: '',
        name: '',
      };
      let userInfo;
      let itemStr = Taro.getStorageSync('b2b-wechat@login');
      let selectDistance = Taro.getStorageSync('selectDistance');
      if (itemStr.user) {
        userInfo = itemStr.user;
      }
      if (selectDistance) {
        dispatch({
          type: Command.init,
          payload: {
            main: {
              communityName: selectDistance.name,
              communityCode: selectDistance.code,
            },
          },
        });
        if (userInfo) {
          //已登录

          // console.log('走这个判断++++++++++++++++++++++++++++++++++')
          let doubleMemModel = Taro.getStorageSync('doubleMemModel'); //弹窗状态
          let memberReceived = Taro.getStorageSync('memberReceived'); //是否领取
          let doubleMemberDate = Taro.getStorageSync('doubleMemberDate');   //缓存的时间
          // let nowTime = moment(new Date()).format('YYYY-MM-DD'); //当前时间
          let serverTime = await api.systemController.queryServerTime();
          let nowTime =  moment(serverTime).format('YYYY-MM-DD');
          // console.log(doubleMemModel, doubleMemberDate, 'aa', nowTime, 'bb', memberReceived, '缓存的时间》》》》》》》》》》》》》》》》')

          if (!memberReceived) {
            if (doubleMemberDate) {
              if (nowTime != doubleMemberDate) {
                // Taro.setStorageSync('doubleMemModel', true);
                action.commonChange('main.doubleMemModel', true);
                Taro.setStorageSync('doubleMemberDate', nowTime);
              }
          } else {
            // Taro.setStorageSync('doubleMemModel', true);
            action.commonChange('main.doubleMemModel', true);
            Taro.setStorageSync('doubleMemberDate', nowTime);
          }
        } else {
          // Taro.setStorageSync('doubleMemModel', false);
          action.commonChange('main.doubleMemModel', false);
        }

        let houseId = '';
        if (userInfo.communityName) {
          //已登录有默认社区
          houseId = userInfo.houseId;
          obj.code = userInfo.communityCode;
          obj.id = userInfo.communityId;
          obj.name = userInfo.communityName;
          this.getDefHouseInfo(userInfo.communityId, userInfo.id);
          Taro.setStorageSync('selectDistance', obj);
        } else {
          //已登录没有社区
          this.getDefHouseInfo(selectDistance.id, userInfo.id);
        }
        // this.findTopN(selectDistance.code);
        // this.advertising(selectDistance.id);
        this.getLotteryButtonShow();
        await this.getBaseConfig(true);
        this.getMemberBase();
        // this.getActiveList(selectDistance.code, userInfo.id);
        // this.findMessage(selectDistance.id, userInfo.id);
        // this.getUrlonce();
        this.findCustomerblacklist(userInfo.phone); //查询黑名单
      } else {
        //未登录
        // this.findTopN(selectDistance.code);
        // this.advertising(selectDistance.id);
        await this.getBaseConfig(false);
        this.resetMemberStatus();
        // this.getUrlonce();
      }
      this.getMemberEquityNum(Boolean(userInfo));
    } else {
      //获取默认社区
      this.getAppCommunity(obj, userInfo);
    }
  },
    resetMemberStatus() {
      action.commonChange('main.isAquamarineMember', false);
      action.commonChange('main.isCrystalMember', false);
      action.commonChange('main.joinMemberModel', false);
      action.commonChange('main.renewalMemberModel', false);
      action.commonChange('main.memberInfo', undefined);
      action.commonChange('main.showDayLotteryButton', false);
      action.commonChange('main.memberCardType', 'noMember');
    },
      /**
       * 获取默认社区
       */
      async getAppCommunity(obj, userInfo) {
    let res = await api.pagesIndexController.findAppCommunity();
    if (res.code == '200') {
      res.data.map((item, index) => {
        if (item.name.includes('明发城市广场') == true) {
          obj.code = item.code;
          obj.name = item.name;
          obj.id = item.id;
          dispatch({
            type: Command.init,
            payload: {
              main: {
                communityName: item.name,
                communityCode: item.code,
              },
            },
          });
          Taro.setStorageSync('selectDistance', obj);
          this.getBaseConfig(false).then(() => {
            this.getMemberEquityNum(Boolean(userInfo));
          });
          this.resetMemberStatus();
          // this.findTopN(item.code);
          // this.advertising(item.id);
          // this.findShopList(false);
          // this.getUrlonce();
        }
      });
    }
  },
    /**
     * 更新用户信息
     */
    async getDefHouseInfo(communityId, userId) {
    let userInfo = Taro.getStorageSync('b2b-wechat@login');
    const params = {
      userId,
      communityId,
    };
    let res = await api.pagesIndexController.findDefHouseByUserId(params);
    if (res.success && res.data) {
      userInfo.user.communityCode = res.data.communityCode;
      userInfo.user.communityId = res.data.communityId;
      userInfo.user.communityName = res.data.communityName;
      userInfo.user.houseId = res.data.houseId;
      userInfo.user.status = res.data.status;
      Taro.setStorageSync('b2b-wechat@login', userInfo);
    } else {
      userInfo.user.communityCode = '';
      userInfo.user.communityId = '';
      userInfo.user.communityName = '';
      userInfo.user.houseId = '';
      userInfo.user.status = '';
      Taro.setStorageSync('b2b-wechat@login', userInfo);
    }
  },
    /**
     * 首页公告
     */
    async findTopN(code) {
    const params = {
      communityCode: code,
    };
    let res = await api.pagesIndexController.getIndexNotices(params);
    if (res.code == '200') {
      dispatch({
        type: Command.init,
        payload: {
          main: {
            noticeList: res.data,
          },
        },
      });
    }
  },
    /**
     * 查询消息数量
     */
    async findMessage(communityId, userId) {
    const params = {
      communityId,
      userId,
    };
    let res = await api.messageController.findTotalMsg(params);
    if (res.code == '200') {
      let unReadNum = 0;
      res.data.map((item, index) => {
        unReadNum += item.unReadNum;
      });
      this.commonChange('main.unReadNum', unReadNum);
    }
  },
    /**
     * 首页轮播图
     */
    async advertising(id) {
    //position,1、首页,2、发现,3、启动页
    const params = {
      type: 1,
      position: 1,
      communityId: id,
    };
    let res = await api.pagesIndexController.getAdverImgs(params);
    if (res.code == '200') {
      dispatch({
        type: Command.init,
        payload: {
          main: {
            banner: res.data.materialList,
          },
        },
      });
    }
  },
    /**
     * 首页推荐政务
     */
    async getUrlonce() {
    let params = {};
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    let selectDistance = Taro.getStorageSync('selectDistance');
    if (itemStr) {
      let userInfo = itemStr.user;
      params = {
        unionId: userInfo.unionId,
        communityId: selectDistance.id,
      };
    } else {
      params = {
        unionId: '',
        communityId: selectDistance.id,
      };
    }
    let res = await api.pagesIndexController.getMegaDataExternalUrl(params);
    if (res.success) {
      let arr = [];
      if (res.data.length == 0) {
        return;
      }
      res.data.map((item, index) => {
        if (item.name == '微心愿' || item.name == '江北民生' || item.name == '食安江北' || item.name == '阳光厨房') {
          arr.push(item);
        }
      });
      action.commonChange('main.ascList', arr);
    }
  },
    /**
     * 首页查询社区活动
     */
    async getActiveList(code, id) {
    let params = {
      registerBy: id,
      num: 1,
      communityCode: code,
      type: '0',
    };
    let res = await api.pagesIndexController.getAppFindList(params);
    if (res.data && res.data.length > 0) {
      action.commonChange('main.activeList', res.data);
    }
  },
    /**
     * 查询商城基本设置
     */
    async getBaseConfig(login) {
    let storeId = Taro.getStorageSync('storeId');
    if (!storeId) {
      let res = await api.pagesIndexController.getBaseConfig();
      if (res.context.storeId) {
        Taro.setStorageSync('storeId', res.context.storeId);
        //查询营销内容（未登录）
        this.unloginfindMarketingcontentPage();
        // this.findShopList(login);
      }
    } else {
      //查询营销内容（未登录）
      this.unloginfindMarketingcontentPage();
      // this.findShopList(login);
    }
  },
    /**
     * 首页查询秒杀
     */
    async findShopList(login) {
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    let storeId = Taro.getStorageSync('storeId');
    Taro.request({
      method: 'GET',
      // mode: 'no-cors',
      url: `${WMkit.prefixUrl(config.renderHost)}/magic/d2cStore/000000/weixin/index?storeId=${storeId}`,
      success: (res) => {
        if (res.data.status == 1 && res.data.result == 'ok' && res.data.data.configOrder) {
          let list = [];
          if (res.data.data.configOrder.children) {
            action.commonChange('main.goodShops', res.data.data.configOrder.children);
          }
          res.data.data.configOrder.children.map((item, index) => {
            // if (item.widgetNameSpace == '@wanmi/wechat-flashlist') {
            //   console.log(res.data.configOrder.children[index].props.items);
            //   action.commonChange('main.shopList', res.data.configOrder.children[index].props.items);
            //   action.flashsaleGoodsList(res.data.configOrder.children[index].props.items)
            // }
            if (item.widgetNameSpace == '@wanmi/wechat-goodslist' && index === 3) {
              // console.log('-----------------------@wanmi/wechat-goodslist');
              // console.log(res.data.configOrder.children[index].props.items);
              action.commonChange('main.shopList', res.data.data.configOrder.children[index].props.items);
              if (item.props.items.length > 0) {
                item.props.items.map((item1, index1) => {
                  list.push(item1.skuId);
                  if (itemStr && itemStr != '') {
                    //  登录后上下架
                    this.goodUpDown(list);
                  } else {
                    // 未登录上下架
                    this.LoginOutSearch(list);
                  }
                });
              }
            }
          });
        }
      },
    });
  },
    /**
     * 查询秒杀商品
     */
    async flashsaleGoodsList(goodList) {
    let list = [];
    goodList.map((item, index) => {
      list.push(item.id);
    });
    let activityFullTimeBegin = moment().subtract(2, 'hour').format('YYYY-MM-DD HH:mm:ss'); //当前时间前两个小时
    let activityFullTimeEnd = moment().add(2, 'day').format('YYYY-MM-DD'); //当前时间后两天
    let params = {
      activityFullTimeBegin, //当前时间前两个小时
      activityFullTimeEnd: activityFullTimeEnd + ' 00:00:00', //当前时间后两天
      idList: list,
    };
    let res = await api.pagesIndexController.getFlashsaleGoodsList(params);
    if (res.code == 'K-000000') {
      if (res.context.flashSaleGoodsVOPage.content.length > 0) {
        action.commonChange('main.shopLists', res.context.flashSaleGoodsVOPage.content);
      }
    }
  },
    async goodUpDown(list) {
    let params = {
      goodsInfoIds: list,
      pageSize: 990,
    };
    let res = await api.pagesIndexController.getSearchShopListLogin(params);
    // console.log('登陆后数据----------', res)
    if (res.code == 'K-000000') {
      action.commonChange('main.shopLists', res.context.esGoodsInfoPage.content);
    }
  },
    async LoginOutSearch(list) {
    let params = {
      goodsInfoIds: list,
      pageSize: 999,
    };
    let res = await api.pagesIndexController.getShopListLoginOut(params);
    if (res.code == 'K-000000') {
      action.commonChange('main.shopLists', res.context.esGoodsInfoPage.content);
    }
    // console.log('未登陆后数据--0000000000--------', res)
  },
    /**
     * 查询内容营销列表（已登录）
     */
    async findMarketingcontentPage() {
    let { pageNum, contentList, selectMemberCard } = getData().main;
    let params = {
      pageNum,
      size: 10,
      isAquamarineMember: ['shuangchong', 'lanjing'].includes(selectMemberCard),
      isCrystalMember: ['shuangchong', 'chijing'].includes(selectMemberCard),
    };
    let result = await api.pagesIndexController.findMarketingcontentPage(params);
    if (result.code == 'K-000000') {
      if (pageNum == 0) {
        action.commonChange('main.contentList', result.context.content);
        action.commonChange('main.totalPages', result.context.totalPage);
      } else {
        let newData = contentList.concat(result.context.content);
        action.commonChange('main.contentList', newData);
        action.commonChange('main.totalPages', result.context.totalPage);
      }
    }
  },
    /**
     * 查询内容营销列表（未登录）
     */
    async unloginfindMarketingcontentPage() {
    let { pageNum } = getData().main;
    let storeId = Taro.getStorageSync('storeId');
    let params = {
      pageNum,
      size: 10,
      storeId,
    };
    let result = await api.pagesIndexController.unloginfindMarketingcontentPage(params);
    if (result.code == 'K-000000') {
      if (pageNum == 0) {
        action.commonChange('main.contentList', result.context.content);
        action.commonChange('main.totalPages', result.context.totalPage);
      } else {
        let newData = contentList.concat(result.context.content);
        action.commonChange('main.contentList', newData);
        action.commonChange('main.totalPages', result.context.totalPage);
      }
    }
  },
    /**
     * 查询黑名单
     */
    async findCustomerblacklist(phone) {
    let result = await api.mobileConfigController.findCustomerblacklist({ customerMobile: phone });
    Taro.setStorageSync('blacklistModel', result.content.length > 0 ? true : false);
    action.commonChange('main.blacklistModel', result.content.length > 0 ? true : false);
  },
};
return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageRzIndexMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
